package xdu.lz.stage2_design_pattern.chapter5_reader_writer_pattern;

import java.util.Random;

public class WriterWorker extends Thread{
    //random sleep time
    public static final Random random = new Random(System.currentTimeMillis());

    private final ShareData shareData;
    //the data will write
    private final String filter;

    private int index = 0;

    public WriterWorker(ShareData shareData, String filter) {
        this.shareData = shareData;
        this.filter = filter;
    }

    @Override
    public void run(){
        try{
            while (true){
                char c = nextChar();
                System.out.println("c = " + c);
                shareData.write(c);
                Thread.sleep(random.nextInt(1000));
            }
        }catch (InterruptedException e){
            System.out.println(Thread.currentThread()+getName()+"线程写操作被中断，结束了任务");
        }

    }

    private char nextChar(){
        char c = filter.charAt(index++);
        if(index >= filter.length()){
            index = 0;
        }
        return c;
    }
}
